package com.phei.netty.chat;

import java.time.LocalDateTime;

import com.phei.netty.Global;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
    	  Channel channel = ctx.channel();
          System.out.println(channel.remoteAddress() + ": " + msg.text());
          //ctx.channel().writeAndFlush(new TextWebSocketFrame("来自服务端: " + LocalDateTime.now()));
        //  Global.writeAndFlush(new TextWebSocketFrame("来自服务端: " + LocalDateTime.now()+"上線")); //服务器发送广播通知
          Global.writeAndFlush(new TextWebSocketFrame("[you]" + msg.text()));
          
         // Global.writeAndFlush("【服务器】: " + ctx.channel().remoteAddress() + "上线"); //服务器发送广播通知
    }
    
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("ChannelId" + ctx.channel().id().asLongText());
    	//Global.writeAndFlush("【服务器】: " + ctx.channel().remoteAddress() + "上线\n"); //服务器发送广播通知
        Global.add(ctx.channel());
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("用户下线: " + ctx.channel().id().asLongText());
    	//Global.write("【服务器】: " + ctx.channel().remoteAddress() + "下线了\n");
    	//Global.remove(ctx.channel());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //ctx.channel().close();
    }
    
    //连接激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println(ctx.channel().remoteAddress() + "上线了");
    	//Global.writeAndFlush(new TextWebSocketFrame("来自服务端: " + LocalDateTime.now()) + "上线\n"); //服务器发送广播通知
    	Global.add(ctx.channel());
    }
    
    //连接断开
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println(ctx.channel().remoteAddress() + "下线了");
    }
    
}